package com.example.test;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class completableFuture02 {

    //不同网站商品查询速度比较
    public static void main(String[] args) {
        ArrayList<network> list = new ArrayList<>();
        network n1 = new network("taobao", "mysql");
        network n2 = new network("tianmao", "mysql");
        network n3 = new network("jindong", "mysql");
        network n4 = new network("pingduoduo", "mysql");
        network n5 = new network("douyin", "mysql");
        network n6 = new network("wuba", "mysql");


        list.add(n1);
        list.add(n2);
        list.add(n3);
        list.add(n4);
        list.add(n5);
        list.add(n6);

        //链式执行
        long startTime = System.currentTimeMillis();
        List<String> collect1 = list.stream().map(network -> String.format(network.getProductName() + " in %s is %.2f", network.getNetName(), network.price())).collect(Collectors.toList());
        for (String s : collect1) {
            System.out.println(s);
        }
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        System.out.println("链式所用时间为: "+totalTime+"ms");
        System.out.println("----------------------------------------------------------------");

        //并发执行
        long startTime2 = System.currentTimeMillis();
        List<String> collect2 = list.stream().map(network -> CompletableFuture.supplyAsync(() -> {
            return String.format(network.getProductName() + " in %s is %.2f", network.getNetName(), network.price());
        })).collect(Collectors.toList()).stream().map((cf) -> cf.join()).collect(Collectors.toList());
        for (String s : collect2) {
            System.out.println(s);
        }
        long endTime2 = System.currentTimeMillis();
        long totalTime2 = endTime2 - startTime2;
        System.out.println("并发所用时间为: "+totalTime2+"ms");
    }


}


@Data
@AllArgsConstructor
@NoArgsConstructor
class network{
    private String netName;
    private String productName;
    public double price(){
        //假定查询时间为一秒
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return 100;
    }
}
